<template>
  <div id="issueAssignDiv">
    <Breadcrumb content="问题分派" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input
                style="width: 180px"
                v-model="searchForm.searchValue"
                type="search" clearable
                class="vxeInputSearch"
                placeholder="关键字查询"
                @clear="findIssueApplyList"
                @keyup="keyupEnter"
                @search-click="findIssueApplyList"></vxe-input>
              <vxe-button type="text"
                class="button-blue"
                icon="vxe-icon-refresh"
                content="刷新"
                :loading="tloading"
                @click="findIssueApplyList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table
              ref="issueApplyTableRef"
              class="mytable-scrollbar"
              border="inner"
              align="center"
              height="auto"
              :data="issueApplyList"
              :loading="tloading"
              @current-change="issueApplyRowClick"
              :row-config="{ isCurrent: true, isHover: true }"
              :column-config="{ resizable: true }"
              resizable show-overflow
              keep-source>
              <vxe-column field="title"
                title="标题" width="120">
              </vxe-column>
              <vxe-column
                field="customerName"
                title="客户名称">
              </vxe-column>
              <vxe-column
                field="priority"
                title="优先级">
                <template
                  #default="{ row }">
                  <el-tag
                    :type="getPriorityTagType(row)">{{ getPriorityDesc(row) }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column
                field="submitterName"
                title="提交人">
              </vxe-column>
              <vxe-column
                field="submitTime"
                title="提交时间">
              </vxe-column>
              <vxe-column field="status"
                title="状态">
                <template
                  #default="{ row }">
                  <el-tag
                    :type="getStatusTagType(row)">{{ getStatusDesc(row) }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column title="操作"
                fixed="right">
                <template
                  #default="{ row }">
                  <vxe-button
                    type="text"
                    status="danger"
                    icon="vxe-icon-close"
                    circle
                    v-if="row.status == 5"
                    @click.native="handleBack(row)"
                    class="spanIcon"></vxe-button>
                  <vxe-button
                    type="text"
                    status="danger"
                    icon="vxe-icon-undo"
                    circle
                    v-if="row.status == 10"
                    @click.native="revoke(row)"
                    class="spanIcon"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
            <vxe-pager align="left"
              min-height="32px"
              :current-page.sync="page.currentPage"
              :page-size.sync="page.pageSize"
              :total="page.totalResult"
              :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'FullJump', 'Total']"
              @page-change="handleSizeChange($event)"></vxe-pager>
          </div>
        </Pane>
        <Pane size="50">
          <div class="form">
            <el-divider
              content-position="left">基本信息</el-divider>
            <el-descriptions
              ref="descriptionsRef"
              class="baseDescriptions"
              :column="3" border
              contentClassName="contentStyle"
              labelClassName="labelWidth">
              <el-descriptions-item
                label="问题分类"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.issueClassifyName : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="问题类型"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.issueTypeName : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="客户名称"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.customerName : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="联系人"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.contactorName : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="联系电话"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.contactorTel : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="项目经理"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.projectManagerName : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="期望完成时间"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.expectFinishTime : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="严重程度"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.severity : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="优先级"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.priority : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="问题来源"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.issueSource : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="分派人" :span="2"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.assignId : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="问题标题" :span="3"
                label-align="right">{{ !isEmpty(sltIssueApply) ? sltIssueApply.title : '' }}</el-descriptions-item>
              <el-descriptions-item
                label="问题描述" :span="3"
                label-align="right">
                <div
                  v-html="!isEmpty(sltIssueApply) ? sltIssueApply.description : ''">
                </div>
              </el-descriptions-item>
            </el-descriptions>
            <el-divider
              content-position="left">任务分派</el-divider>
            <el-button type="success"
              @click="addAssign"
              :disabled="sltIssueApply.status!=5"
              class="addHandlerPeople">添加处理人</el-button>
            <el-scrollbar
              :style="{ height: 'calc(100% - 24px  - ' + elScrollbarHeight + 'px - 24px - 40px - 40px - 15px)' }">
              <el-card class="box-card"
                v-for="(assignForm,index) in assignList"
                :key="index"
                shadow="hover">
                <el-form
                  :ref="'assignForm'+(index+1)"
                  :rules="assignFormRule"
                  :model="assignForm"
                  label-width="110px"
                  class="form-input-m"
                  :inline="true"
                  :inline-message="true"
                  style="width:800px"
                  :disabled="sltIssueApply.status!=5">
                  <el-form-item
                    prop="requiredFinishTime"
                    label="要求完成时间">
                    <el-date-picker
                      v-model="assignForm.requiredFinishTime"
                      type="date"
                      placeholder="期望完成时间"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD" />

                  </el-form-item>
                  <el-form-item
                    prop="requiredFinishHours"
                    label="预计工时">
                    <el-input
                      type="text"
                      v-model="assignForm.requiredFinishHours">
                      <template
                        slot="append">小时</template>
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    prop="assignerId"
                    label="处理人">
                    <el-select
                      :ref="'assignerSelect'+(index+1)"
                      v-model="assignForm.assignerId"
                      placeholder="请选择处理人"
                      clearable
                      filterable
                      style="width: 200px;">
                      <el-option
                        v-for="item in userList"
                        :key="item.id"
                        :label="item.realname"
                        :value="item.id"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item
                    prop="isCloser"
                    label="是否是关闭人">
                    <el-switch
                      v-model="assignForm.isCloser"
                      inline-prompt
                      active-text="是"
                      inactive-text="否"></el-switch>
                  </el-form-item>
                  <el-form-item
                    prop="remark"
                    label="任务备注">
                    <el-input
                      type="textarea"
                      :autosize="{minRows:5}"
                      v-model="assignForm.remark"
                      placeholder="请输入备注"
                      style="width: 436px"
                      :rows="5"></el-input>
                  </el-form-item>
                </el-form>
                <el-button
                  class="del-deal"
                  type="danger"
                  :disabled="sltIssueApply.status!=5"
                  @click="deleteAssign(index)">删除</el-button>
              </el-card>
              <div class="ml20">
                <el-button
                  type="primary"
                  :loading="subing"
                  @click="submitAssign()"
                  :disabled="sltIssueApply.status!=5">分派</el-button>
                <el-button type="danger"
                  :loading="reting"
                  @click="retBug()"
                  :disabled="sltIssueApply.status!=5">退回</el-button>
              </div>
            </el-scrollbar>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '@/stores/store';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import moment from 'moment';

let store = AppStore();
let searchForm = {
  searchValue: ''
};
let tloading = ref(false);
let issueApplyList: any = reactive([]); //质控规则列表表格
let sltIssueApply: any = ref({});
let assignList: any = reactive([]);
let userList: any = reactive([]);

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
let subing = ref(false); //分配按钮加载状态
let reting = ref(false); //退回按钮加载状态
let elScrollbarHeight = ref(100); //添加处理人下方card 滚动条高度
onMounted(() => {
  findIssueApplyList(); // 获取质控规则表格数据
  getUserOptions();
});

function getUserOptions() {
  const url = '/api/user/getUserInfoList';
  proxy.$http
    .get(url, {})
    .then((res: any) => {
      userList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取所有用户选项 (下拉框)失败', VxeNotifyType.error);
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findIssueApplyList();
  }
}
//点击每页数量(分页查询)
function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findIssueApplyList();
}

function findIssueApplyList() {
  tloading.value = true;
  issueApplyList.length = 0; //放入数据前清空数据
  const url = '/api/wk/wkIssueApply/findIssueApplyPageList';
  const obj = {
    seachValue: searchForm.searchValue,
    assignId: store.userInfo.id,
    pageIndex: page.currentPage,
    pageSize: page.pageSize,
    statuss: '5,10'
  };
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: obj
    })
    .then((res: any) => {
      issueApplyList.push(...res.data.records);
      page.totalResult = res.data.total;
      tloading.value = false;
      const kn = issueApplyList.find((k) => k.id == sltIssueApply.value.id);
      if (isEmpty(kn)) {
        issueApplyRowClick({ row: issueApplyList[0] }); //默认选中第一条数据
      } else {
        issueApplyRowClick({ row: kn }); //默认选中第一条数据
      }
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 获取元素高度变化
function updateDescriptionsHeight() {
  // 获取类名为 baseDescriptions 的 el-descriptions 元素
  let baseDescriptionsList = null;
  baseDescriptionsList = proxy.$refs.descriptionsRef;
  // 只处理第一个匹配的元素
  if (baseDescriptionsList) {
    let baseDescriptions = baseDescriptionsList.$el.offsetHeight;
    // 获取当前元素的高度
    elScrollbarHeight.value = baseDescriptions;
    // console.log('监听的高度点击el', elScrollbarHeight.value);
  }
}

// 点击设计模式表格当前行触发右侧表单变化
function issueApplyRowClick({ row }: any) {
  assignList.length = 0;
  if (isEmpty(row)) {
    //clearForm();
    sltIssueApply.value = {};
  } else {
    (proxy.$refs.issueApplyTableRef as any).setCurrentRow(row);
    sltIssueApply.value = row;
    findIssueAssignList();
  }
}
function findIssueAssignList() {
  assignList.length = 0; //放入数据前清空数据
  const url = '/api/wk/wkIssueAssign/findIssueAssignList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        applyId: sltIssueApply.value.id
      }
    })
    .then((res: any) => {
      assignList.push(...res.data);

      if (isEmpty(assignList)) {
        assignList.push({
          id: '',
          applyId: sltIssueApply.value.id,
          assignerId: '',
          assignTime: '',
          requiredFinishTime: '',
          requiredFinishHours: '',
          finishTime: '',
          finishHours: '',
          isCloser: true,
          remark: '',
          status: 0,
          orgId: ''
        });
      }
      updateDescriptionsHeight(); //动态更新高度
    })
    .catch((err: any) => {
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function retBug() {
  handleBack(sltIssueApply.value);
}

function revoke(row: any) {
  proxy
    .$confirm('确定撤回？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/wk/wkIssueApply/revokeIssueApply';
      let obj = {
        id: row.id,
        status: 5
      };
      proxy.$http.post(url, obj).then((res: any) => {
        if (res.status.code === 1) {
          findIssueApplyList();
          VxeMessage('撤回成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function handleBack(row: any) {
  proxy
    .$confirm('确定退回？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/wk/wkIssueApply/reBackIssueApply';
      let obj = {
        id: row.id,
        status: 1
      };
      proxy.$http.post(url, obj).then((res: any) => {
        if (res.status.code === 1) {
          findIssueApplyList();
          VxeMessage('退回成功', VxeNotifyType.success);
        } else {
          VxeMessage(res.status.msg, VxeNotifyType.error);
        }
      });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
let assignForm = reactive({
  id: '',
  applyId: '',
  assignerId: '',
  assignTime: '',
  requiredFinishTime: '',
  requiredFinishHours: '',
  finishTime: '',
  finishHours: '',
  isCloser: true,
  remark: '',
  status: 0,
  orgId: ''
});

let assignFormRule = {
  requiredFinishTime: [
    {
      required: true,
      message: '请选择要求完成时间',
      trigger: 'blur'
    }
  ],
  assignerId: [
    {
      required: true,
      message: '请选择分派人',
      trigger: 'blur'
    }
  ]
};
function addAssign() {
  assignList.push({
    id: '',
    applyId: sltIssueApply.value.id,
    assignerId: '',
    assignTime: '',
    requiredFinishTime: '',
    requiredFinishHours: '',
    finishTime: '',
    finishHours: '',
    isCloser: true,
    remark: '',
    status: 0,
    orgId: ''
  });
}
function deleteAssign(index: number) {
  proxy
    .$confirm('确定要删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      this.assignList.splice(index, 1);
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
async function submitAssign() {
  let array: any = [];
  assignList.forEach((item, index) => {
    const ela: any = proxy.$refs['assignForm' + (index + 1)];
    array.push(
      new Promise((resolve, reject) => {
        ela[0].validate((valid) => {
          if (valid) {
            resolve();
          } else {
            reject(new Error('错误'));
          }
        });
      })
    );
  });
  Promise.all(array)
    .then(() => {
      //验证成功后在此处发请求
      const cloerNum = assignList.filter((p: any) => p.isCloser);
      if (!cloerNum || cloerNum.length === 0 || cloerNum.length > 1) {
        VxeMessage('请选择一位关闭人', VxeNotifyType.error);
        return;
      }
      proxy
        .$confirm('确定分派？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          subing.value = true;
          const sveOrupdateDetail = [] as any[];
          assignList.forEach((e: any) => {
            const assign: any = {
              id: e.id,
              applyId: e.applyId,
              assignerId: e.assignerId,
              assignTime: e.assignTime,
              requiredFinishTime: isEmpty(e.requiredFinishTime) ? '' : moment(new Date(e.requiredFinishTime)).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
              requiredFinishHours: e.requiredFinishHours,
              finishTime: e.finishTime,
              finishHours: e.finishHours,
              isCloser: e.isCloser,
              remark: e.remark,
              status: e.status,
              orgId: e.orgId
            };

            sveOrupdateDetail.push(assign);
          });
          if (sveOrupdateDetail.length > 0) {
            const url = '/api/wk/wkIssueAssign/submitAssign';
            const obj: any = { id: sltIssueApply.value.id, status: 10 };
            obj.assignList = sveOrupdateDetail;
            proxy.$http
              .post(url, obj)
              .then((res: any) => {
                VxeMessage('更新成功', VxeNotifyType.success);
                findIssueApplyList();
                subing.value = false;
              })
              .catch((err: any) => {
                VxeMessage('更新失败', VxeNotifyType.success);
              });
          } else {
            VxeMessage('无添加或修改数据', VxeNotifyType.error);
          }
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
    })
    .catch(() => {
      // console.log('222222222222');
    });
}
function getStatusTagType(row: any) {
  const status = row.status;
  if (status === 0 || status === 1) {
    return 'info';
  } else if (status === 5) {
    return 'danger';
  } else if (status === 10) {
    return 'warning';
  } else if (status === 15) {
    return 'warning';
  } else if (status === 20) {
    return '';
  } else if (status === 35) {
    return 'success';
  } else {
    return '';
  }
}

// 获取是否静态文字(是/否)
function getStatusDesc(row: any) {
  const status = row.status;
  switch (status) {
    case 0:
      return '暂存';
    case 1:
      return '退回';
    case 5:
      return '待分派';
    case 10:
      return '待开始';
    // return '待分派开发';
    // case 11:
    //   return '待分派实施';
    case 15:
      return '待开始';
    case 20:
      return '处理中';
    case 35:
      return '已关闭';
  }
}

function getPriorityTagType(row: any) {
  const value = row.priority;
  if (value === '1') {
    return 'danger';
  } else if (value === '2') {
    return 'warning';
  } else if (value === '3') {
    return '';
  } else if (value === '4') {
    return 'success';
  } else {
    return '';
  }
}

function getPriorityDesc(row: any) {
  const type = row.priority;
  switch (type) {
    case '1':
      return '高';
    case '2':
      return '较高';
    case '3':
      return '一般';
    case '4':
      return '较低';
  }
}
</script>
<style lang="scss" scoped>
#issueAssignDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      //右侧 基本信息 任务分派
      .form {
        height: 100%;
        //添加处理人
        .addHandlerPeople {
          margin-left: 10px;
        }
        .box-card {
          margin: 10px;
          position: relative;
          .el-card__body {
            padding-bottom: 15px;
          }
          // card内删除
          .del-deal {
            position: absolute;
            right: 10px;
            top: 10px;
          }
        }
        .ml20 {
          margin: 10px 0 5px 140px;
        }
      }
    }
  }
}
</style>
